package com.qh.yyxt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.qh.yyxt.entity.*;
import com.qh.yyxt.mapper.FlagMapper;
import com.qh.yyxt.mapper.ThingMapper;
import com.qh.yyxt.mapper.ThingSizeMapper;
import com.qh.yyxt.pojo.*;
import com.qh.yyxt.pojo.entity.thing.Thing;
import com.qh.yyxt.pojo.entity.thing.ThingSize;
import com.qh.yyxt.pojo.entity.meeting.User;
import com.qh.yyxt.service.BorrowThingService;
import com.qh.yyxt.service.DelayThingService;
import com.qh.yyxt.service.FlagService;
import com.qh.yyxt.service.ThingService;
import com.qh.yyxt.utils.UploadFileUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
public class AdminBorrowThingController
{
    @Autowired
    private BorrowThingService borrowThingService;
    @Autowired
    private FlagService flagService;
    @Autowired
    private ThingService thingService;
    @Autowired
    private ThingSizeMapper thingSizeMapper;
    @Autowired
    private DelayThingService delayThingService;
    @Autowired
    private FlagMapper flagMapper;
    @Autowired
    private ThingMapper thingMapper;
    //role1审批请求(0 拒绝 1 通过)
    @RequestMapping("/admin/doBorrowThingApply")
    @ResponseBody
    public String passBorrowThingApply(@RequestParam("fid") String fid,@RequestParam("approver")String approver,String mark)
    {
//        Integer id = Integer.parseInt(fid);
//        Flag flag = flagMapper.selectById(id);
//        flag.setApprover(approver);
//        flag.setState(mark.equals("0")?"未通过":"审批通过");
//        int i = flagMapper.updateById(flag);
//        if(i>0){
//
//        }
//        else return "操作失败";

        try {
            Integer fId=Integer.parseInt(fid);
            String state="";
            if(mark.equals("1")) {
                state="审批通过";
                //判断每个数量是不是都小于对应的thingsize数量！
                //说明没冲突
                if(borrowThingService.judgeAllThingSize(fId))
                {
                    //对应物品减掉对应的数量
                    Map<Integer,Integer> map=new LinkedHashMap<>();
                    List<BorrowThing>borrowThingList=borrowThingService.findBorrowThingByFid(fId);
                    for(BorrowThing borrowThing:borrowThingList)
                    {
                        if(map.containsKey(borrowThing.getTid()))
                        {
                            int n=map.get(borrowThing.getTid());
                            map.put(borrowThing.getTid(),n+borrowThing.getNum());
                        }else{
                            map.put(borrowThing.getTid(),borrowThing.getNum());
                        }
                    }
                    if(borrowThingService.updateThingANdSizeNum(map,fId)==0) {
//                        System.out.println(map.toString()+" "+fId);
//                        System.out.println(111);
                        return "操作失败！";
                    }
                    if(borrowThingService.updateStateByFid(fId,state)==0){
//                        System.out.println(222);
                        return "操作失败！";
                    }

                }else{//数量不合适
                    return "审批失败，物品部分申请数量大于库存！";
                }
            }
            else {
//                System.out.println("else这里");
                state="未通过";
                if(borrowThingService.updateStateByFid(fId,state)==0)
                    return "操作失败！";
            }
            if(flagService.updateInfoById(fId,new Date(),approver,null,state)==1)
            {
//                System.out.println("==1这里");
                return "操作成功！";
            }else{
                return "操作失败！";
            }
        } catch (NumberFormatException e)
        {
            //e.printStackTrace();
            return "记录编号异常！";
        }
    }
    //管理员审批记录展示
    @RequestMapping("/admin/findFlagDTO")
    @ResponseBody
    public List<FlagDTO> findFlagDTOByUid()
    {
        User user=(User)SecurityUtils.getSubject().getPrincipal();
        if(user.getRole().equals("1")||user.getRole().equals("2")){
            return  flagService.findByState("待审批");
        }
        else return null;
    }
    //查看某一个申请的详情
    @RequestMapping("/user/findAllDetail")
    @ResponseBody
    public BorrowThingInfoDTO findFlagDTODetail(String fid)
    {
        User user=(User)SecurityUtils.getSubject().getPrincipal();
        if(user.getRole().equals("0"))
            return null;
        if(fid==null) return null;
        Integer fId= null;
        try {
            fId = Integer.parseInt(fid);
            return borrowThingService.findByFid(fId);
        } catch (NumberFormatException e)
        {
            //e.printStackTrace();
        }
        return null;
    }
    //查看归还详情的端口
    @RequestMapping("/user/findReturnDetail")
    @ResponseBody
    public BorrowThingInfoDTO findReturnDetail(String fid)
    {
        User user=(User)SecurityUtils.getSubject().getPrincipal();
        if(user.getRole().equals("0"))
            return null;
        if(fid==null) return null;
        Integer fId= null;
        try {
            fId = Integer.parseInt(fid);
            System.out.println(fid);
            System.out.println();
            BorrowThingInfoDTO dto = borrowThingService.findByState(fId, "已借出");
            System.out.println(dto);
            return dto;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }
    //显示历史记录
    //历史记录的列表
    @RequestMapping("/user/borrowThingHistory")
    @ResponseBody
    public List<FlagDTO> findBorrowThingHistory()
    {
        User user=(User)SecurityUtils.getSubject().getPrincipal();

        if(user.getRole().equals("1")||user.getRole().equals("2")){
//            QueryWrapper<Flag> wrapper = new QueryWrapper<>();
//            wrapper.eq("state","审批通过").or()
//                    .eq("state","未通过");
//            return flagMapper.selectList(wrapper);
//            return flagService.findByTwoState("未归还","已归还");

            return flagService.findByTwoState("审批通过","未通过");
        }
        else return null;
    }
    //显示历史记录的详情
    @RequestMapping("/user/borrowThingHistoryDetail")
    @ResponseBody
    public BorrowThingInfoDTO findBorrowThingHistoryDetail(String fid)
    {
        System.out.println(fid);
        User user=(User)SecurityUtils.getSubject().getPrincipal();
        if(!user.getRole().equals("1")&&!user.getRole().equals("2"))
            return null;
        if(fid==null) return null;
        Integer fId= null;
        try {
            fId = Integer.parseInt(fid);
            return borrowThingService.findByFid(fId);
        } catch (NumberFormatException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    //导出word
    @RequestMapping("/user/exportWord")
    @ResponseBody
    public void exportWord(String fid, HttpServletResponse response)
    {

        User user=(User)SecurityUtils.getSubject().getPrincipal();
        if(!user.getRole().equals("1")&&!user.getRole().equals("2"))
            return;
        if(fid==null) return;
        Integer fId= null;
        try
        {
            fId = Integer.parseInt(fid);
            BorrowThingInfoDTO borrowThingInfoDTO=borrowThingService.findByFid(fId);
             borrowThingService.export(borrowThingInfoDTO,response);
        } catch (NumberFormatException e)
        {
            //e.printStackTrace();
        }

        return;
    }
    //添加物品
    @RequestMapping("/user/addThing")
    @ResponseBody
    //让前端算完总数传给我 Thing thing, @RequestBody List<ThingSize> list
    public String addThing(@RequestBody JsonForMe jsonForMe)
    {
        User user=(User)SecurityUtils.getSubject().getPrincipal();
        if(!user.getRole().equals("1")&&!user.getRole().equals("2"))
            return "无权限!";
        Thing thing=jsonForMe.getThing();
        List<ThingSize>list=jsonForMe.getThingSizeList();
        int tId=thingService.addThing(thing);
        for(ThingSize thingSize:list)
        {
            thingSize.setTid(tId);
        }
        thingSizeMapper.addList(list);
        return "添加成功";
    }
    @Autowired
    UploadFileUtil fileUtil;
    //上传图片
    @RequestMapping("/user/addImg")
    @ResponseBody
    public String addImg(MultipartFile file){
        System.out.println(file);
        String url = fileUtil.uploadFile(file);
        if(url==null||"".equals(url)) return null;
        Gson gson = new Gson();
        String rtn = gson.toJson("url:"+url);
        return rtn;
    }
    //修改物品
    @RequestMapping("user/updateThing")
    @ResponseBody
    public String updateThing(@RequestBody JsonForMe jsonForMe)
    {
        System.out.println(jsonForMe);
        User user=(User)SecurityUtils.getSubject().getPrincipal();
        if(!user.getRole().equals("1")&&!user.getRole().equals("2"))
            return "无权限";
        Thing thing=jsonForMe.getThing();
        List<ThingSize>list=jsonForMe.getThingSizeList();
        if(thingService.updateInfo(thing)==0)
        {
            return "修改失败";
        }
        for (ThingSize thingSize:list)
        {
            thingSizeMapper.update(thingSize);
        }
        return "修改成功！";
    }
    //删除物品规格！
    @RequestMapping("user/deleteThingSize")
    @ResponseBody
    public String deleteThing(String sId)
    {
        User user=(User)SecurityUtils.getSubject().getPrincipal();
        if(!user.getRole().equals("1")&&!user.getRole().equals("2"))
            return "无权限";
        if(sId==null)
            return "id不能为空";
        int sid=Integer.parseInt(sId);
        if(borrowThingService.findBySid(sid)!=null)
        {
            return "该物品正在使用中或已被申请，无法删除！";
        }
        ThingSize thingSize=thingSizeMapper.findById(sid);
        //System.out.println(thingSize);
        Thing thing=thingService.findThingById(thingSize.getTid());
        thing.setNum(thing.getNum()-thingSize.getNum());
        thing.setRenum(thing.getRenum()-thingSize.getRenum());
        thingService.updateNum(thing.getId(),thing.getNum(),thing.getRenum());
        //如果这是最后一个规格的话 那么就删除物品及规格、以及所有的记录
        if(thing.getNum()==0)
        {
            thingService.delete(thing.getId());
            thingSizeMapper.delete(thingSize.getId());
            borrowThingService.deleteByTid(thingSize.getTid());
        }
        //如果这不是最后一个物品，那么就删除规格以及所有的规格借用记录
        else{
            thingSizeMapper.delete(thingSize.getId());
            borrowThingService.deleteBySid(thingSize.getId());
        }
        return "操作成功！";
    }

    //查看延时申请
    @RequestMapping("admin/findDelayThing")
    @ResponseBody
    public List<FlagDTO>findDelayThing()
    {
        return delayThingService.findList();
    }
    //查看某一个的延时申请详情
    @RequestMapping("admin/findDelayThingDetail")
    @ResponseBody
    public BorrowThingInfoDTO findDelayThingDetail(Integer fid)
    {
        if(fid==null) return null;
        return delayThingService.findDetail(fid);
    }
    //审批延时请求 id delaystate
    @RequestMapping("admin/updateDelayThingState")
    @ResponseBody
    public String updateDelayThingState(DelayThing delayThing)
    {
       return delayThingService.update(delayThing);
    }

    @RequestMapping("/user/searchThings")
    @ResponseBody
    @Transactional
    public SThingDTO searchThings(Integer id){
        Thing things = thingMapper.selectById(id);
        SThingDTO th = new SThingDTO();
        BeanUtils.copyProperties(things,th);
        th.setSizeList(thingSizeMapper.selectList(new QueryWrapper<ThingSize>().eq("tid",things.getId())));
        System.out.println(th);
        return th;
    }
    @RequestMapping("/user/searchTs")
    @ResponseBody
    public List<Thing> searchTs(){
        List<Thing>things = thingMapper.selectList(null);
        return things;
    }
}
